package com.fan.cachewebview.utils

import android.app.Application
import android.os.Build
import android.os.SystemClock
import android.util.Log
import androidx.annotation.RequiresApi

/**
 * @description $
 * @date: 2022/5/9 14:06
 * @author: fan
 */
object PreloadEngineUtil {
    @RequiresApi(api = Build.VERSION_CODES.M)
    fun preloadWebView(app: Application) {
        try {
            app.mainLooper.queue.addIdleHandler {
                startChromiumEngine()
                false
            }
        } catch (t: Throwable) {
            Log.v("fanLoad", "Oops!", t)
        }
    }

    private fun startChromiumEngine() {
        try {
            val t0 = SystemClock.uptimeMillis()
            val provider = Reflection.invokeStaticMethod<Any>(
                Class.forName("android.webkit.WebViewFactory"),
                "getProvider"
            )
            Reflection.invokeMethod<Any>(
                provider, "startYourEngines", arrayOf<Class<*>?>(
                    Boolean::class.javaPrimitiveType
                ), arrayOf<Any>(true)
            )
            Log.v(
                "fanLoad",
                "Start chromium engine complete: " + (SystemClock.uptimeMillis() - t0) + " ms"
            )
        } catch (t: Throwable) {
            Log.v("fanLoad", "Start chromium engine error", t)
        }
    }
}